package com.yuliang.controller;


import com.yuliang.domain.R;
import com.yuliang.domain.entity.LoginUser;
import com.yuliang.domain.entity.Menu;
import com.yuliang.domain.entity.User;
import com.yuliang.domain.vo.AdminUserInfoVo;
import com.yuliang.domain.vo.RoutersVo;
import com.yuliang.domain.vo.UserInfoVo;
import com.yuliang.enums.AppHttpCodeEnum;
import com.yuliang.exception.SystemException;
import com.yuliang.service.BlogLoginService;
import com.yuliang.service.LoginService;
import com.yuliang.service.MenuService;
import com.yuliang.service.RoleService;
import com.yuliang.utils.BeanCopyUtils;
import com.yuliang.utils.SecurityUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Api(description = "后台管理系统登入相关接口")
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleService roleService;

    @PostMapping("/user/login")
    public R login(@RequestBody User user){
        if (!StringUtils.hasText(user.getUserName())){
            //return R.errorResult(AppHttpCodeEnum.REQUIRE_USERNAME);  ??
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return loginService.login(user);
    }

    @PostMapping("/user/logout")
    public R logout(){
        return loginService.logout();
    }

    @GetMapping("/getInfo")
    public R getInfo(){
        //获取当前登入用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        //根据用户id获取权限信息
        List<String> permissions = menuService.selectPermsByUserId(loginUser.getUser().getId());
        //根据用户id获取角色信息
        List<String> roles = roleService.selectRoleKeyByUserId(loginUser.getUser().getId());
        //获取用户信息
        User user = loginUser.getUser();
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);

        return R.okResult(new AdminUserInfoVo(permissions,roles,userInfoVo));
    }

    @GetMapping("/getRouters")
    public R<RoutersVo> getRouters(){
        Long userId = SecurityUtils.getUserId();
        return menuService.getRouters(userId);

        //method2
        //查询menu 结果是tree的形式
//        List<Menu> menus = menuService.selectRouterMenuTreeByUserId(userId);
//        //封装数据返回
//        return R.okResult(new RoutersVo(menus));
    }
}